package com.andy.servlet;

import com.andy.infrastructure.ioc.BeanFactory;
import com.andy.infrastructure.ioc.impl.DefaultBeanFactory;
import com.andy.infrastructure.pojo.Result;
import com.andy.infrastructure.util.JsonUtils;
import com.andy.service.TransferService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class TransferServlet extends HttpServlet {

    private BeanFactory beanFactory;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置编码
        req.setCharacterEncoding("UTF-8");

        String fromCardNo = req.getParameter("fromCardNo");
        String toCardNo = req.getParameter("toCardNo");
        String moneyStr = req.getParameter("money");
        double amount = Double.parseDouble(moneyStr);

        Result result = new Result();
        try {
            // 2. 调用service层方法
            TransferService transferService = (TransferService)beanFactory.getBean(TransferService.class);
            transferService.transferMoney(fromCardNo,toCardNo,amount);
            result.setStatus("200");
        } catch (Exception e) {
            e.printStackTrace();
            result.setStatus("201");
            result.setMessage(e.toString());
        }

        // 响应
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().print(JsonUtils.object2Json(result));

    }

    @Override
    public void init() throws ServletException {
        beanFactory = new DefaultBeanFactory();
        try {
            beanFactory.initBeanFactory("com.andy");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
